/*
Copyright (c) [2019年5月1日] [吴超]
[MBT_studio] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
#include "stdafx.h"
#include "lua自动补齐.h"

#include <sstream>
#include <algorithm>
#include <cctype>

using namespace std;



// 内置模块数据库
static vector<ModuleInfo> buildModuleDatabase() {
	vector<ModuleInfo> modules;

	// 1. 核心模块
	ModuleInfo base("base");
	base.members = {"print", "assert", "error", "ipairs", "pairs", "next", "type", "tonumber", "tostring",
		"select", "unpack", "load", "loadstring", "dofile", "require", "getmetatable", "setmetatable"};
	modules.push_back(base);

	// 2. IO模块
	ModuleInfo io("io");
	io.members = {"open", "close", "read", "write", "flush", "lines", "stdin", "stdout", "stderr",
		"input", "output", "tmpfile", "popen", "exit"};
	modules.push_back(io);

	// 3. 文件系统模块
	ModuleInfo fs("fs");
	fs.members = {"readdir", "stat", "mkdir", "rmdir", "unlink", "rename", "exists", "copy", 
		"writeFile", "readFile", "chmod", "realpath", "symlink"};
	modules.push_back(fs);

	// 4. 网络模块
	ModuleInfo net("net");
	net.members = {"createServer", "connect", "Socket", "Server", "listen", "accept", "send", "recv",
		"close", "setTimeout", "setKeepAlive"};
	net.submodules = {"http", "tcp", "udp", "tls"};
	modules.push_back(net);

	// 网络子模块
	ModuleInfo http("net.http");
	http.members = {"get", "post", "put", "delete", "request", "createServer", "createClient",
		"parseUrl", "formatUrl", "Server", "Client"};
	modules.push_back(http);

	// 5. 字符串模块
	ModuleInfo str("string");
	str.members = {"len", "sub", "rep", "char", "byte", "find", "match", "gsub", "upper", "lower",
		"reverse", "format", "dump", "pack", "unpack"};
	modules.push_back(str);

	// 6. 表模块
	ModuleInfo tab("table");
	tab.members = {"insert", "remove", "concat", "sort", "pack", "unpack", "length", "copy"};
	modules.push_back(tab);

	// 7. 数学模块
	ModuleInfo math("math");
	math.members = {"abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "cosh", "deg", "exp",
		"floor", "fmod", "frexp", "ldexp", "log", "log10", "max", "min", "modf", "pi",
		"pow", "rad", "random", "randomseed", "sin", "sinh", "sqrt", "tan", "tanh"};
	modules.push_back(math);

	// 8. 日期时间模块
	ModuleInfo date("date");
	date.members = {"now", "parse", "format", "utc", "local", "diff", "add", "sub",
		"isLeapYear", "getDayOfWeek", "getMonthDays"};
	modules.push_back(date);

	// 9. 正则表达式模块
	ModuleInfo regex("regex");
	regex.members = {"match", "search", "find", "replace", "split", "compile",
		"escape", "test", "exec", "flags"};
	modules.push_back(regex);

	// 10. FFI模块
	ModuleInfo ffi("ffi");
	ffi.members = {
		"cdef", "typeof", "new", "cast", "string", "copy", "fill", 
		"offsetof", "alignof", "sizeof", "gc", "load", "errno", 
		"seterr", "geterr"
	};
	ffi.submodules = {"types", "lib", "callbacks"};
	modules.push_back(ffi);

	// FFI子模块
	ModuleInfo ffiTypes("ffi.types");
	ffiTypes.members = {
		"void", "int8", "uint8", "int16", "uint16",
		"int32", "uint32", "int64", "uint64",
		"float", "double", "pointer", "cdata",
		"char", "short", "int", "long", "longlong"
	};
	modules.push_back(ffiTypes);

	// 11. 加密模块
	ModuleInfo crypto("crypto");
	crypto.members = {"md5", "sha1", "sha256", "sha512", "hmac", "cipher", 
		"decipher", "randomBytes", "pbkdf2", "hash"};
	crypto.submodules = {"aes", "rsa", "ecdsa"};
	modules.push_back(crypto);

	// 12. JSON模块
	ModuleInfo json("json");
	json.members = {"encode", "decode", "stringify", "parse", "prettyPrint",
		"schemaValidate", "minify"};
	modules.push_back(json);

	// 13. 操作系统模块
	ModuleInfo os("os");
	os.members = {"exit", "getenv", "setenv", "remove", "rename", "tmpname",
		"execute", "clock", "date", "time", "difftime"};
	modules.push_back(os);

	// 14. 进程模块
	ModuleInfo process("process");
	process.members = {"argv", "env", "cwd", "chdir", "exit", "pid", "ppid",
		"stdin", "stdout", "stderr", "kill", "on"};
	modules.push_back(process);

	return modules;
}

// 全局模块数据库
static vector<ModuleInfo> g_modules = buildModuleDatabase();

// Lua内部函数列表（需排除）
static const unordered_set<string> luaInternalFunctions = {
	"print", "assert", "error", "ipairs", "pairs", "type", "tonumber", "tostring"
};




// 查找模块信息
static const ModuleInfo* findModule(const string& moduleName) {
	for (const auto& module : g_modules) {
		if (module.name == moduleName) {
			return &module;
		}
	}
	return nullptr;
}

// 处理require导入的变量提取
vector<CodeElement> extractImportedModules(const string& 已有代码) {
	vector<CodeElement> imported;
	string code = 已有代码;
	size_t pos = 0;
	const string requirePattern = "require%(";

	while ((pos = code.find(requirePattern, pos)) != string::npos) {
		pos += requirePattern.size();

		// 查找字符串引号
		char quote = '\0';
		if (pos < code.size() && (code[pos] == '"' || code[pos] == '\'')) {
			quote = code[pos];
			pos++;
		} else {
			continue; // 不规范的require格式
		}

		// 提取模块名
		size_t endQuote = code.find(quote, pos);
		if (endQuote == string::npos) break;

		string moduleName = code.substr(pos, endQuote - pos);
		pos = endQuote + 1;

		// 查找赋值变量名 (local xxx = require(...))
		size_t eqPos = code.rfind('=', pos);
		if (eqPos == string::npos) continue;

		size_t varStart = eqPos;
		while (varStart > 0 && isspace(code[varStart-1])) varStart--;
		while (varStart > 0 && (isalnum(code[varStart-1]) || code[varStart-1] == '_')) varStart--;

		string varName;
		if (varStart < eqPos) {
			varName = code.substr(varStart, eqPos - varStart);
			varName = trim(varName);

			// 检查是否有local关键字
			size_t localPos = code.rfind("local", varStart);
			if (localPos != string::npos) {
				varStart = localPos + 5; // "local"长度
				while (varStart < eqPos && isspace(code[varStart])) varStart++;
				varName = code.substr(varStart, eqPos - varStart);
				varName = trim(varName);
			}
		}

		// 如果没有显式变量名，使用模块名作为变量名
		if (varName.empty()) {
			size_t lastDot = moduleName.find_last_of('.');
			if (lastDot != string::npos) {
				varName = moduleName.substr(lastDot + 1);
			} else {
				varName = moduleName;
			}
		}

		// 添加导入的模块变量
		imported.emplace_back(varName, CodeElementType::TABLE, moduleName);

		unordered_set<string> added;
		//if (added.find(varName) == added.end()) {
		//	added.insert(varName);
			imported.emplace_back(varName, CodeElementType::TABLE, moduleName);

			// 添加模块成员作为子元素
			const ModuleInfo* module = findModule(moduleName);
			if (module) {
				for (const string& member : module->members) {
					imported.emplace_back(member, CodeElementType::FUNCTION, varName);
				}
			}
		//}
	}

	return imported;
}

// 提取所有代码元素（函数、变量、类型、结构等）
static vector<CodeElement> extractAllCodeElements(const string& 已有代码) {
	vector<CodeElement> elements;
	unordered_set<string> addedElements; 
	string code = 已有代码;
	size_t pos = 0;

	// 1. 提取函数
	const string funcStr = "function";
	while ((pos = code.find(funcStr, pos)) != string::npos) {
		pos += funcStr.size();

		// 跳过空格
		while (pos < code.size() && isspace(code[pos])) pos++;

		// 提取函数名
		size_t nameEnd = pos;
		while (nameEnd < code.size() && (isalnum(code[nameEnd]) || code[nameEnd] == '_' || code[nameEnd] == '.')) {
			nameEnd++;
		}

		if (nameEnd > pos) {
			string funcName = code.substr(pos, nameEnd - pos);

			//if (addedElements.find(funcName) == addedElements.end()) {
			//	addedElements.insert(funcName);

				// 检查是否为成员函数
				size_t dotPos = funcName.find_last_of('.');
				if (dotPos != string::npos) {
					elements.emplace_back(funcName.substr(dotPos + 1), CodeElementType::FUNCTION, funcName.substr(0, dotPos));
				} 
				else {
					elements.emplace_back(funcName, CodeElementType::FUNCTION);
				}
			//}
		}
		pos++;
	}

	// 2. 提取变量（简单赋值语句）
	pos = 0;
	while (pos < code.size()) {
		// 跳过字符串和注释
		if (code[pos] == '"' || code[pos] == '\'') {
			char quote = code[pos];
			pos++;
			while (pos < code.size() && code[pos] != quote) {
				if (code[pos] == '\\' && pos + 1 < code.size()) pos++;
				pos++;
			}
			if (pos < code.size()) pos++;
			continue;
		}
		if (pos + 1 < code.size() && code[pos] == '-' && code[pos+1] == '-') {
			pos += 2;
			while (pos < code.size() && code[pos] != '\n') pos++;
			continue;
		}

		// 查找赋值运算符
		size_t eqPos = code.find('=', pos);
		if (eqPos == string::npos) break;

		// 提取变量名
		size_t varEnd = eqPos - 1;
		while (varEnd > pos && isspace(code[varEnd])) varEnd--;

		size_t varStart = varEnd;
		while (varStart > pos && (isalnum(code[varStart]) || code[varStart] == '_' || code[varStart] == '.')) {
			varStart--;
		}
		varStart++;

		if (varStart <= varEnd) {
			string varName = code.substr(varStart, varEnd - varStart + 1);
			// 检查是否为成员变量
			size_t dotPos = varName.find_last_of('.');
			if (dotPos != string::npos) {
				elements.emplace_back(varName.substr(dotPos + 1), CodeElementType::VARIABLE, varName.substr(0, dotPos));
			} else {
				elements.emplace_back(varName, CodeElementType::VARIABLE);
			}
		}

		pos = eqPos + 1;
	}

	// 3. 提取结构体/表定义
	pos = 0;
	const string structPattern = "struct";
	while ((pos = code.find(structPattern, pos)) != string::npos) {
		pos += structPattern.size();

		// 跳过空格
		while (pos < code.size() && isspace(code[pos])) pos++;

		// 提取结构体名
		size_t nameEnd = pos;
		while (nameEnd < code.size() && (isalnum(code[nameEnd]) || code[nameEnd] == '_')) {
			nameEnd++;
		}

		if (nameEnd > pos) {
			string structName = code.substr(pos, nameEnd - pos);
			elements.emplace_back(structName, CodeElementType::STRUCT);

			// 提取结构体成员（假设用{}包裹）
			size_t braceStart = code.find('{', nameEnd);
			if (braceStart != string::npos) {
				size_t braceEnd = code.find('}', braceStart);
				if (braceEnd != string::npos) {
					string structContent = code.substr(braceStart + 1, braceEnd - braceStart - 1);
					istringstream iss(structContent);
					string line;
					while (getline(iss, line)) {
						size_t colonPos = line.find(':');
						if (colonPos != string::npos) {
							string memberName = line.substr(0, colonPos);
							memberName = trim(memberName);
							if (!memberName.empty()) {
								elements.emplace_back(memberName, CodeElementType::VARIABLE, structName);
							}
						}
					}
				}
			}
		}
		pos++;
	}

	// 4. 提取表定义（Lua风格）
	pos = 0;
	while (pos < code.size()) {
		size_t tableStart = code.find('{', pos);
		if (tableStart == string::npos) break;

		// 查找表名（等号左边）
		size_t eqPos = code.rfind('=', tableStart);
		if (eqPos != string::npos) {
			size_t nameStart = eqPos - 1;
			while (nameStart > pos && isspace(code[nameStart])) nameStart--;
			while (nameStart > pos && (isalnum(code[nameStart]) || code[nameStart] == '_')) nameStart--;
			nameStart++;

			if (nameStart < eqPos) {
				string tableName = code.substr(nameStart, eqPos - nameStart);
				tableName = trim(tableName);
				if (!tableName.empty()) {
					elements.emplace_back(tableName, CodeElementType::TABLE);

					// 提取表字段
					size_t tableEnd = code.find('}', tableStart);
					if (tableEnd != string::npos) {
						string tableContent = code.substr(tableStart + 1, tableEnd - tableStart - 1);
						istringstream iss(tableContent);
						string line;
						while (getline(iss, line)) {
							size_t eqPos = line.find('=');
							if (eqPos != string::npos) {
								string fieldName = line.substr(0, eqPos);
								fieldName = trim(fieldName);
								// 去除可能的引号
								if ((fieldName.front() == '"' && fieldName.back() == '"') ||
									(fieldName.front() == '\'' && fieldName.back() == '\'')) {
									fieldName = fieldName.substr(1, fieldName.size() - 2);
								}
								if (!fieldName.empty()) {
									elements.emplace_back(fieldName, CodeElementType::VARIABLE, tableName);
								}
							}
						}
					}
				}
			}
		}

		pos = tableStart + 1;
	}

	// 5. 新增：提取逻辑判断和控制结构关键字（仅添加此部分，不修改原有逻辑）
	vector<pair<string, CodeElementType>> keywords = {
		// 条件判断
		{"if",			CodeElementType::CONTROL_STRUCT},
		{"else",		CodeElementType::CONTROL_STRUCT},
		{"elseif",		CodeElementType::CONTROL_STRUCT},
		{"then",		CodeElementType::CONTROL_STRUCT},

		// 循环结构
		{"for",			CodeElementType::CONTROL_STRUCT},
		{"while",		CodeElementType::CONTROL_STRUCT},
		{"do",			CodeElementType::CONTROL_STRUCT},
		{"repeat",		CodeElementType::CONTROL_STRUCT},
		{"until",		CodeElementType::CONTROL_STRUCT},

		// 流程控制
		{"break",		CodeElementType::KEYWORD},
		{"continue",	CodeElementType::KEYWORD},
		{"return",		CodeElementType::KEYWORD},

		// 其他结构
		{"end",			CodeElementType::CONTROL_STRUCT},
		{"in",			CodeElementType::KEYWORD},
		{"local",		CodeElementType::KEYWORD},
		{"global",		CodeElementType::KEYWORD},

		{"require",		CodeElementType::KEYWORD},
		{"import",		CodeElementType::KEYWORD},
		{"export",		CodeElementType::KEYWORD},
		{"from",		CodeElementType::KEYWORD},
		{"as",			CodeElementType::KEYWORD},
		{"and",			CodeElementType::KEYWORD},
		{"or",			CodeElementType::KEYWORD},
		{"not",			CodeElementType::KEYWORD},
		{"nil",			CodeElementType::KEYWORD},
		{"true",		CodeElementType::KEYWORD},
		{"false",		CodeElementType::KEYWORD}
	};

	// 添加关键字到代码元素
	for (const auto& [kw, type] : keywords) {
		elements.emplace_back(kw, type);
	}

	// 添加导入的模块和模块成员
	vector<CodeElement> imported = extractImportedModules(已有代码);
	elements.insert(elements.end(), imported.begin(), imported.end());

	return elements;
}


// 工具函数：修剪字符串（处理前后空格）
string trim(const string& s) {
	if (s.empty()) return "";
	size_t start = 0, end = s.size() - 1;
	while (start <= end && isspace(s[start])) start++;
	while (end >= start && isspace(s[end])) end--;
	return s.substr(start, end - start + 1);
}

// 工具函数：移除字符串中所有空格
string removeSpaces(const string& s) {
	string res;
	for (char c : s) {
		if (!isspace(c)) res += c;
	}
	return res;
}

// 快速前缀匹配（忽略空格影响）
inline int32 fastPrefixMatch(const string& 前缀, const string& 目标) {
	if (前缀.empty()) return 0;  // 前缀为空时不匹配任何内容
	if (目标.size() < 前缀.size()) return 0;

	int matchLength = 0;
	for (size_t i = 0; i < 前缀.size(); ++i) {
		if (tolower(前缀[i]) != tolower(目标[i])) {
			return 0;  // 不匹配
		}
		matchLength++;
	}

	// 返回匹配长度，用于排序
	return matchLength;
}

// 检测是否处于函数定义阶段
bool isInFunctionDefinition(const string& 已有代码, string& 函数名) {
	// 1. 组合已有代码和当前输入，形成完整上下文
	string fullContext = 已有代码;

	// 2. 查找最后出现的"function"关键字
	size_t functionKeywordPos = fullContext.rfind("function");
	if (functionKeywordPos == string::npos) {
		return false;
	}

	// 3. 检查在这个"function"之后是否已经出现了"end"
	size_t endKeywordPos = fullContext.rfind("end");
	if (endKeywordPos != string::npos && endKeywordPos > functionKeywordPos) {
		return false;
	}

	// 4. 提取"function"关键字后面的函数名
	size_t afterFunction = functionKeywordPos + string("function").size();

	// 跳过中间的空格
	while (afterFunction < fullContext.size() && isspace(fullContext[afterFunction])) {
		afterFunction++;
	}

	// 提取函数名（字母、数字、下划线组成）
	size_t functionNameStart = afterFunction;
	while (afterFunction < fullContext.size() && 
		   (isalnum(fullContext[afterFunction]) || fullContext[afterFunction] == '_')) {
		afterFunction++;
	}

	// 函数名不能为空
	if (afterFunction <= functionNameStart) {
		return false;
	}

	// 保存提取到的函数名
	函数名 = fullContext.substr(functionNameStart, afterFunction - functionNameStart);
	return true;
}

// 检测函数名是否需排除
bool isFunctionExcluded(const string& functionName, const unordered_set<string>& definedFunctions, bool excludeInternal) {
	// 始终排除已定义函数
	if (definedFunctions.count(functionName)) {
		return true;
	}
	// 根据参数决定是否排除内部函数
	if (excludeInternal && luaInternalFunctions.count(functionName)) {
		return true;
	}
	return false;
}

// 提取代码中已定义的函数名
unordered_set<string> extractDefinedFunctions(const string& code) {
	unordered_set<string> functions;
	size_t pos = 0;
	const string funcStr = "function";

	while ((pos = code.find(funcStr, pos)) != string::npos) {
		pos += funcStr.size();

		// 跳过所有空格
		while (pos < code.size() && isspace(code[pos])) pos++;

		// 提取函数名
		size_t nameEnd = pos;
		while (nameEnd < code.size() && (isalnum(code[nameEnd]) || code[nameEnd] == '_')) {
			nameEnd++;
		}

		if (nameEnd > pos) {
			string funcName = code.substr(pos, nameEnd - pos);
			functions.insert(funcName);
		}
		pos++;
	}

	return functions;
}

unordered_set<string> extractDefinedFunctions(const S_文档文本& doc) {
	unordered_set<string> functions;
	size_t pos = 0;
	const string funcStr = "function";

	for (auto& 文本块 : doc.m_文本块) {
		auto code = f_str_u16_to_u8(文本块.m_一行);

		while ((pos = code.find(funcStr, pos)) != string::npos) {
			pos += funcStr.size();

			// 跳过所有空格
			while (pos < code.size() && isspace(code[pos])) pos++;

			// 提取函数名
			size_t nameEnd = pos;
			while (nameEnd < code.size() && (isalnum(code[nameEnd]) || code[nameEnd] == '_')) {
				nameEnd++;
			}

			if (nameEnd > pos) {
				string funcName = code.substr(pos, nameEnd - pos);
				functions.insert(funcName);
			}
			pos++;
		}
	}
	
	return functions;
}

// 获取上下文前缀（当前输入的最后一部分）
static string getContextPrefix(const string& 当前输入) {
	size_t 最后空格 = 当前输入.find_last_of(" \t\n\r");
	if (最后空格 == string::npos) return 当前输入;
	return 当前输入.substr(最后空格 + 1);
}

// 处理补全结果排序和提取
static vector<string> getCompletionResults(vector<CompletionItem>& 补全列表) {
	// 按优先级排序，优先级相同则按名称排序
	sort(补全列表.begin(), 补全列表.end(),
		 [](const CompletionItem& a, const CompletionItem& b) {
		if (a.priority != b.priority) {
			return a.priority > b.priority;
		}
		return a.content > b.content;
	});

	vector<string> res;
	for (const auto& item : 补全列表) {
		res.push_back(item.content);
	}
	return res;
}

// 分析当前代码上下文类型
static ContextType analyzeContext(const string& 已有代码, const string& 当前输入, string& 函数名) {
	
	// 检查函数定义
	if (isInFunctionDefinition(已有代码, 函数名)) {
		return ContextType::FUNCTION_DEFINITION;
	}

	
	// 检查if块
	size_t ifPos = 已有代码.rfind("if");
	size_t thenPos = 已有代码.rfind("then");
	size_t ifEndPos = 已有代码.rfind("end");
	

	// 如果存在then且在if之后，且没有结束
	if (thenPos != string::npos && ifPos != string::npos && thenPos > ifPos &&
		(ifEndPos == string::npos || thenPos > ifEndPos)) {
		return ContextType::IF_THEN_BLOCK;
	}

	// 新增：检查if块（在then之前）
	if (ifPos != string::npos && (ifEndPos == string::npos || ifPos > ifEndPos)) {
		return ContextType::IF_BLOCK;
	}

	// 检查循环块
	vector<string> loops = {"for", "while", "repeat"};
	for (const string& loop : loops) {
		size_t loopPos = 已有代码.rfind(loop);
		if (loopPos != string::npos && (ifEndPos == string::npos || loopPos > ifEndPos)) {
			return ContextType::LOOP_BLOCK;
		}
	}

	return ContextType::NORMAL;
}

// 获取结构补全模板
static vector<pair<string, int32>> getStructureTemplates(ContextType 上下文类型, const string& 前缀) {
	vector<pair<string, int32>> templates;

	switch (上下文类型) {
		case ContextType::NORMAL:
			// 普通上下文下的结构补全
			templates = {
				{"if 条件 then\nend", 400},
				{"for i = 1, 10 do\nend", 380},
				{"while 条件 do\nend", 370},
				{"local 变量名 = 值", 350},
				{"function 函数名()\nend", 360}
			};
			break;

		case ContextType::FUNCTION_DEFINITION:
			// 函数定义中的补全
			templates = {
				{"(参数1, 参数2)\nend", 400},
				{"()\nend", 390},
				{"(...) \nend", 380}
			};
			break;

		case ContextType::IF_BLOCK:  // 新增：if条件后专门补全then
			templates = {
				{"then\n", 500},  // 高优先级，then后自动换行
				{"then", 490}
			};
			break;

		case ContextType::IF_THEN_BLOCK:  // 新增：if...then之后的补全
			templates = {
				{"end", 400},
				{"else\n", 390},
				{"elseif 条件 then\n", 380}
			};
			break;

		case ContextType::LOOP_BLOCK:
			// 循环块中的补全
			templates = {
				{"end", 400},
				{"break", 350},
				{"continue", 340}
			};
			break;
	}

	return templates;
}

// 辅助函数：解析完整的成员访问路径
static vector<string> parseMemberPath(const string& input) {
	vector<string> path;
	string current;

	for (char c : input) {
		if (c == '.') {
			if (!current.empty()) {
				path.push_back(current);
				current.clear();
			}
		} 
		else {
			current += c;
		}
	}

	// 添加最后一个部分（可能不完整）
	if (!current.empty()) {
		path.push_back(current);
	}

	return path;
}

// 辅助函数：查找指定路径的父元素
static string findParentElement(const vector<CodeElement>& elements, const vector<string>& path, size_t level) {
	if (level == 0) return "";  // 顶级元素没有父级

	// 构建到当前层级的完整路径
	string fullPath;
	for (size_t i = 0; i < level; ++i) {
		if (i > 0) fullPath += ".";
		fullPath += path[i];
	}

	// 查找是否存在这个完整路径的元素
	for (const auto& elem : elements) {
		string elemFullPath = elem.parent.empty() ? elem.name : elem.parent + "." + elem.name;
		if (elemFullPath == fullPath) {
			return elem.name;
		}
	}

	// 如果找不到不存在，尝试查找最短匹配
	for (const auto& elem : elements) {
		if (elem.parent.empty() && level == 1 && 
			elem.name.substr(0, path[0].size()) == path[0]) {
			return elem.name;
		}
	}

	return "";
}


// 获取函数补全候选（只保留必要项）
vector<string> getGeneralCompletions(const string& 当前输入, const std::string& code, const unordered_set<string>& definedFunctions, bool excludeInternal) {
	vector<CompletionItem> completions;
	string 上下文前缀 = getContextPrefix(当前输入);

	// 1. 提取所有代码元素
	vector<CodeElement> 代码元素 = extractAllCodeElements(code);

	// 1. 分析当前上下文类型
	string 函数名;
	ContextType 上下文类型 = analyzeContext(code, 当前输入, 函数名);

	// 2. 添加结构补全（新增核心部分）
	vector<pair<string, int>> 结构模板 = getStructureTemplates(上下文类型, 上下文前缀);
	for (const auto& [tpl, prio] : 结构模板) {
		int match = fastPrefixMatch(上下文前缀, tpl);
		if (match > 0) {
			string 补全内容 = tpl.substr(上下文前缀.size());
			
			// 修剪补全内容开头的空格
			size_t start = 补全内容.find_first_not_of(" \t");
			if (start != string::npos) {
				补全内容 = 补全内容.substr(start);
			} 
			else {
				补全内容 = "";  // 全是空格则不补全
			}

			if (!补全内容.empty()) {
				// 匹配长度越长，优先级越高
				completions.push_back(CompletionItem(补全内容, prio + match * 10, "structure"));
			}
		}
	}

	// 3. 添加关键字补全（新增）
	for (const auto& elem : 代码元素) {
		if ((elem.type == CodeElementType::KEYWORD || elem.type == CodeElementType::CONTROL_STRUCT) &&
			elem.parent.empty()) {

			int match = fastPrefixMatch(上下文前缀, elem.name);
			if (match > 0) {
				int basePriority = 300;
				
				int priority = basePriority + match * 20;  // 匹配长度权重更高

				// if块中then的特殊优先级
				if (上下文类型 == ContextType::IF_BLOCK && elem.name == "then") {
					priority += 100;  // then在if块中优先级更高
				}

				string 补全内容 = elem.name.substr(上下文前缀.size());

				if (补全内容.empty()) {  // 完全匹配时
					if (elem.name == "if" || elem.name == "for" || elem.name == "while" || elem.name == "elseif") {
						补全内容 += " ";
					} else if (elem.name == "then" || elem.name == "do") {
						补全内容 += "\n";
					}
				}

				completions.push_back(CompletionItem(补全内容, priority, 
													 elem.type == CodeElementType::KEYWORD ? "keyword" : "control_struct"));
			}
		}
	}

	// 4. 保留原有的函数和变量补全
	for (const auto& elem : 代码元素) {
		if ((elem.type == CodeElementType::FUNCTION || elem.type == CodeElementType::VARIABLE ||
			 elem.type == CodeElementType::STRUCT || elem.type == CodeElementType::TABLE) &&
			elem.parent.empty() && 上下文类型 != ContextType::FUNCTION_DEFINITION) {

			string 类型字符串;
			int basePriority = 0;

			switch (elem.type) {
				case CodeElementType::FUNCTION: 
					类型字符串 = "function"; 
					basePriority = 250;
					break;
				case CodeElementType::VARIABLE: 
					类型字符串 = "variable"; 
					basePriority = 200;
					break;
				case CodeElementType::STRUCT: 
					类型字符串 = "struct"; 
					basePriority = 280;
					break;
				case CodeElementType::TABLE: 
					类型字符串 = "table"; 
					basePriority = 270;
					break;
				default: 
					continue;
			}

			int match = fastPrefixMatch(上下文前缀, elem.name);
			if (match > 0) {
				int32 priority = basePriority + match * 15;

				string 补全内容 = elem.name.substr(上下文前缀.size()) + 
					(elem.type == CodeElementType::FUNCTION ? "()" : "");
				completions.push_back(CompletionItem(补全内容, priority, 类型字符串));
			}
		}
	}

	// 5. 添加内置类型补全
	vector<pair<string, string>> builtinTypes = {
		{"number", "type"},
		{"string", "type"},
		{"boolean", "type"},
		{"table", "type"},
		{"function", "type"},
		{"nil", "type"}
	};

	for (const auto& [typeName, type] : builtinTypes) {
		int match = fastPrefixMatch(上下文前缀, typeName);
		if (match > 0) {
			string 补全内容 = typeName.substr(上下文前缀.size());
			completions.push_back(CompletionItem(补全内容, 150 + (match == 2 ? 50 : 0), type));
		}
	}

	return getCompletionResults(completions);
}


vector<string> getMemberCompletions(const string& 已有代码, const string& 当前输入) {
	vector<CompletionItem> completions;
	string contextPrefix = getContextPrefix(当前输入);

	// 解析输入中没有点，不进行成员补全
	if (contextPrefix.find('.') == string::npos) {
		return {};
	}

	// 分析上下文，字符串和注释中不提供成员补全
	string dummy;
	ContextType contextType = analyzeContext(已有代码, 当前输入, dummy);
	if (contextType == ContextType::STRING_CONTEXT || 
		contextType == ContextType::COMMENT_CONTEXT) {
		return {};
	}


	// 解析成员访问路径
	vector<string> memberPath = parseMemberPath(contextPrefix);
	bool isPartial = (contextPrefix.back() != '.');  // 是否以点结尾（是否是完整路径）
	size_t currentLevel = isPartial ? memberPath.size() - 1 : memberPath.size();

	// 获取当前层级的父元素名称
	vector<CodeElement> 代码元素 = extractAllCodeElements(已有代码);
	string parentName = findParentElement(代码元素, memberPath, currentLevel);

	// 如果找不到直接父元素，尝试尝试上一级
	if (parentName.empty() && currentLevel > 0) {
		parentName = findParentElement(代码元素, memberPath, currentLevel - 1);
	}

	// 处理多级路径的完整父名（如 "code.code"）
	string fullParentName;
	for (size_t i = 0; i < currentLevel && i < memberPath.size(); ++i) {
		if (i > 0) fullParentName += ".";
		fullParentName += memberPath[i];
	}

	// 支持两种匹配方式：精确匹配父名或完整路径匹配
	for (const auto& elem : 代码元素) {
		bool match = false;

		// 情况1：精确匹配父级是完整路径（如 "code.code"）
		if (!fullParentName.empty() && elem.parent == fullParentName) {
			match = true;
		}
		// 情况2：父级是简单名称，且路径最后一部分匹配
		else if (!parentName.empty() && elem.parent == parentName) {
			match = true;
		}
		// 情况3：处理根级元素（第一级）
		else if (currentLevel == 0 && elem.parent.empty()) {
			match = true;
		}

		if (match) {
			// 获取当前正在输入的部分（路径最后一部分）
			string currentPart = memberPath.empty() ? "" : memberPath.back();
			int matchLength = fastPrefixMatch(currentPart, elem.name);

			if (matchLength > 0 || (!isPartial && currentPart.empty())) {
				string 补全内容;
				int basePriority = 300;

				if (isPartial) {
					// 残缺输入：补全当前成员名的剩余部分
					补全内容 = elem.name.substr(currentPart.size());
				} else {
					// 完整路径（以点结尾）：补全整个成员名
					补全内容 = elem.name;
				}

				// 如果是函数，添加括号
				if (elem.type == CodeElementType::FUNCTION && 
					(isPartial || currentPart != elem.name)) {
					补全内容 += "()";
				}

				// 多级路径的优先级调整：层级越深优先级略低
				int levelPenalty = currentLevel * 5;
				int priority = basePriority + matchLength * 20 - levelPenalty;

				completions.push_back(CompletionItem(补全内容, priority, 
													 elem.type == CodeElementType::FUNCTION ? "function" : "variable"));
			}
		}
	}

	// 模块成员补全支持
	if (memberPath.size() >= 1) {
		string moduleVarName = memberPath[0];

		// 查找变量对应的模块名
		string moduleName;
		for (const auto& elem : 代码元素) {
			if (elem.name == moduleVarName && elem.type == CodeElementType::TABLE) {
				moduleName = elem.parent; // parent存储的是模块名
				break;
			}
		}

		// 如果找到模块，添加模块成员补全
		if (!moduleName.empty()) {
			const ModuleInfo* module = findModule(moduleName);
			if (module) {
				string currentPart = memberPath.back();
				bool isPartial = (contextPrefix.back() != '.');

				// 补全模块成员
				for (const string& member : module->members) {
					int match = fastPrefixMatch(currentPart, member);
					if (match > 0 || (!isPartial && currentPart.empty())) {
						string completion;
						if (isPartial) {
							completion = member.substr(currentPart.size());
						} else {
							completion = member;
						}

						// 函数成员添加括号
						if (completion == member) {
							completion += "()";
						} else if (member.substr(currentPart.size()) == completion) {
							completion += "()";
						}

						int priority = 350 + match * 20; // 模块成员优先级略高
						completions.push_back(CompletionItem(completion, priority, "module_member"));
					}
				}

				// 补全子模块
				for (const string& submod : module->submodules) {
					int match = fastPrefixMatch(currentPart, submod);
					if (match > 0 || (!isPartial && currentPart.empty())) {
						string completion;
						if (isPartial) {
							completion = submod.substr(currentPart.size());
						} else {
							completion = submod;
						}

						int priority = 340 + match * 20;
						completions.push_back(CompletionItem(completion, priority, "submodule"));
					}
				}
			}
		}
	}

	return getCompletionResults(completions);
}



